package com.cci.kangdao.controller;

import com.cci.kangdao.crmapi.CRMApiUtils;
import com.cci.kangdao.crmapi.CRMResponeEntity;
import com.cci.kangdao.crmapi.CRMServiceConst;
import com.cci.kangdao.service.CRMPlatformService;
import com.cci.kangdao.utilTool.ParameterTool;
import com.cci.kangdao.utilTool.PublicTool;
import net.sf.json.JSONObject;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;

@Controller
public class CRMPlatformController {
    /**
     * 1、日志
     */
    private static final Logger LOG = Logger.getLogger(CRMPlatformController.class);

    @Autowired
    private CRMPlatformService crmPlatformService;


    /**
     * 测试接口
     * 当前接口只是用来测试是否能同步信息到crm
     */
    @RequestMapping("/syncFaultLocationToCRM.aspx")
    public void syncFaultLocationToCRM(HttpServletRequest request, HttpServletResponse response) {

		try {
			Map<String, Object> map = ParameterTool.getParameterRequest(request, true);
			CRMResponeEntity crmResp = CRMApiUtils.getCRMServiceApi().syncFaultLocationToCRM(map);
			ParameterTool.writeResponse(response, crmResp.getStatus(), crmResp.getMessage());
		} catch (Exception e) {
			ParameterTool.writeResponse(response, -100, e.getMessage());
		}
    }




    /**
     * CRM接口
     *
     * @param request
     * @param response
     * @return
     */
    @RequestMapping("/crmApi.aspx")
    public ModelAndView syncOrderInfo(HttpServletRequest request, HttpServletResponse response) {

        try {
            Map<String, Object> map = ParameterTool.getParameterRequest(request, true);
            map.put("response", response);
            map.put("request", request);

            Map<String, Object> headerMap = this.getHeadersInfo(request);
            LOG.info("SF请求的参数为 : " + (map));
            // 验证token是否对应
            if (CRMServiceConst.IS_CRMHEADER_ADDMD5) {
                if (!headerMap.containsKey(CRMServiceConst.CRM_REQUEST_HEADER_TOKEN)
                        || !map.containsKey(CRMServiceConst.CRM_REQUEST_COMPANY)
                        || !map.containsKey(CRMServiceConst.CRM_REQUEST_SYSTEMTIME)) {
                    this.missingNecessaryParams(response, "缺少请求参数");
                    return null;
                }
                String token = headerMap.get("token").toString();
                String company = map.get(CRMServiceConst.CRM_REQUEST_COMPANY).toString();
                String systemTime = map.get(CRMServiceConst.CRM_REQUEST_SYSTEMTIME).toString();
                if (token.length() > 0 && company.length() > 0 && systemTime.length() > 0) {
                    String md5ToToken = PublicTool.compute(String.format("%s+%s", company, systemTime));
                    if (!token.equals(md5ToToken)) {
                        this.missingNecessaryParams(response, "请求参数传递不正确");
                        return null;
                    }
                } else {
                    this.missingNecessaryParams(response, "必须参数不能为空");
                    return null;
                }
            }

            // 根据funName 确认具体接口
            if (map.containsKey(CRMServiceConst.CRM_REQUEST_FUNNAME)) {

                String funName = map.get(CRMServiceConst.CRM_REQUEST_FUNNAME).toString();
                if (funName.equals(CRMServiceConst.CRMCREATWORKORDER_TOAPP)) {
                    return crmPlatformService.createWorkOrderFromCRM(map);
                } else if (funName.equals(CRMServiceConst.CRMGETWORKORDERPICTURES_FROMAPP)) {
                    return crmPlatformService.getOrderPictureInfos(map);
                } else if (funName.equals(CRMServiceConst.CRMSYNCSTATIONINFO_TOAPP)) {
                    return crmPlatformService.syncServiceStationInfosFromCRM(map);
                } else if (funName.equals(CRMServiceConst.CRMGETTRACKINFO_FROMAPP)) {
                    return crmPlatformService.getWorkOrderTracks(map);
                } else if (funName.equals(CRMServiceConst.CRMSYNCSTATIONUSERINFO_TOAPP)) {
                    return crmPlatformService.syncEngineerQualifyInfos(map);
                } else if (funName.equals(CRMServiceConst.CRMSYNCPOSITIONINFO_TOAPP)) {
                    String companyStr = map.get("company").toString();
                    if (companyStr.equals(CRMServiceConst.DBU)) {
                        return crmPlatformService.syncPositionInfoDub(map);
                    }
                    return crmPlatformService.syncPositionInfo(map);
                } else if (funName.equals(CRMServiceConst.CRMSYNCEXCEPTIONS_TOAPP)) {
                    return crmPlatformService.syncExceptionsToApp(map);
                } else if (funName.equals(CRMServiceConst.CRMSYNCWORKORDERINFO_TOAPP)) {
                    return crmPlatformService.updateCRMWorkOrderInfo(map);
                } else if (funName.equals(CRMServiceConst.CRMSYNCUPDATEEXCEPTIONWORKORDER_TOCRM)) {
                    return crmPlatformService.manualUpdateWorkOrderInfo(map);
                } else if (funName.equals(CRMServiceConst.CRMSYNCCRMORDERSTATUS_TOAPP)) {    //ljk   2.2.4 CRM系统同步工单状态到APP系统
                    return crmPlatformService.syncCRMOrderStatus(map);
                } else if (funName.equals(CRMServiceConst.CRMSYNCQUALIFICATIONINFO_TOAPP)) {
                    return crmPlatformService.syncQualificationInfo(map);
                } else if (funName.equals(CRMServiceConst.CRMUPDATEENGINEINFO_TOAPP)) {
                    return crmPlatformService.updateEngineInfo(map);
                } else if (funName.equals(CRMServiceConst.CRM_SYNC_ERROR_PICTURES_TO_APP)) {
                    crmPlatformService.syncErrorPictures(map);
                }else if(funName.equals(CRMServiceConst.CRM_SYNC_GETDIAGNOSTICMSGBYDRORDERNO)){
                    crmPlatformService.getDiagnosticMsgByDROrderNo(map);
                } else if (funName.equals(CRMServiceConst.CRM_SYNC_GETSMNBYESN)){
                    return crmPlatformService.getSMNByESN(map);
                }else if (funName.equals(CRMServiceConst.CCEC_SYNC_PART_INFO_TO_APP)) {
                    return crmPlatformService.syncPartInfos(map);
                } else if (funName.equals(CRMServiceConst.CCEC_SYNC_ENGINE_INFO_TO_APP)) {
                    return crmPlatformService.syncEngineInfos(map);
                } else if (funName.equals(CRMServiceConst.CCEC_SYNC_ORDER_INFO_TO_APP)) {
                    crmPlatformService.createWorkOrderFromCCEC(map);
                } else if (funName.equals(CRMServiceConst.CCEC_SYNC_ORDER_STATUS_TO_APP)) {
                    crmPlatformService.syncCrmOrderStatusFromCCEC(map);
                } else if (funName.equals(CRMServiceConst.CCEC_SYNC_EXCEPTION_INFO_TO_APP)) {
                    crmPlatformService.syncExceptionsToApp(map);
                } else if (funName.equals(CRMServiceConst.CRM_SYNC_WOCLOSEREQUEST)) {
                    return crmPlatformService.syncWOCloseRequest(map);
                } else if (funName.equals(CRMServiceConst.CRM_SYNC_SERVICESUBTYPE)) {
                    // TODO >>同步服务工单服务子类型
                	crmPlatformService.crmSyncServiceSubType(map);
                }else if (funName.equals(CRMServiceConst.CRM_CALL_APP_SENDSMS)) {
                    // 微信公众号开发 CRM推送短信给用户，让用户更新位置
                	crmPlatformService.crmCallAPPSendSMS(map);
                }else if (funName.equals(CRMServiceConst.CRM_400_CANCEL_WORKORDER)) {
                    //  400坐席 400主管取消服务工单
                    crmPlatformService.crmCallAPPCancelWO(map);
                } else if (funName.equals(CRMServiceConst.DDCR_CANCEL_STATIONAUTHORIZATION)) {
                    // DDCR发起取消经销商授权接口
                    crmPlatformService.ddcrCancelStationAuthorization(map);
                }else if (funName.equals(CRMServiceConst.CRMEXPERTSOLUTION_TOAPP)) {
                    // 主动升级中DBU同步专家给出的解决方案
                    crmPlatformService.escalation(map);
                } else if (funName.equals(CRMServiceConst.SYNC_INDIVIDUAL_CASES_SAVE)) {
                    // dub  同步工单超时原因个案详情    vr
                    crmPlatformService.syncIndividualCasesSave(map);
                } else {
                    this.missingNecessaryParams(response, "请求参数传递不正确");
                }
			}else // 没有传递funName参数
			{
				this.missingNecessaryParams(response,"缺少请求参数");
			}
			return null;
		}catch(Exception ex){
			LOG.error(ex.getMessage(),ex);
			String msg = "{\"status\": -99,\"msg\": \"未知错误\"}";
			ParameterTool.writeResponse(response, msg);
		}
		return null;
	}

    @RequestMapping("/getTrackPages.aspx")
    public ModelAndView getTrackPages(HttpServletRequest request, HttpServletResponse response) {
        try {
            Map<String, Object> map = ParameterTool.getParameterRequest(request, true);
            map.put("response", response);
            map.put("request", request);
            return crmPlatformService.getTrackPages(map);
        } catch (Exception ex) {
            LOG.error(ex.getMessage(), ex);
            ParameterTool.writeErrorResponse(response);
        }
        return null;
    }

	/**
	 * get request headers
	 * @Title: getHeadersInfo
	 * @Description: TODO(这里用一句话描述这个方法的作用)
	 * @param @param request
	 * @param @return
	 * @return Map<String,String>
	 * @throws
	 */
	 private Map<String, Object> getHeadersInfo(HttpServletRequest request) {
	   Map<String, Object> map = new HashMap<String, Object>();
	   Enumeration headerNames = request.getHeaderNames();
	   while (headerNames.hasMoreElements()) {
	     String key = (String) headerNames.nextElement();
	     String value = request.getHeader(key);
	     map.put(key, value);
	   }
	   return map;
	 }

	 /**
	  * 缺少必须参数
	  * @Title: missingNecessaryParams
	  * @Description: TODO(这里用一句话描述这个方法的作用)
	  * @param @param response
	  * @return void
	  * @throws
	  */
	 public void missingNecessaryParams(HttpServletResponse response,String message) {
		//暂无此方法
		JSONObject obj = new JSONObject();
		obj.put("status", 1);
		obj.put("msg", message);
		obj.put("data", "");
		ParameterTool.writeResponse(response, obj.toString());
		obj = null;
	}
}
